package com.qdxwx.data.service.help;

import com.qdxwx.common.cache.CacheUtils;
import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.entity.Ztree;
import com.qdxwx.data.mapper.help.HelpMapper;
import com.qdxwx.models.help.Help;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Service
public class HelpServiceImpl implements HelpService {
	@Autowired
	private HelpMapper helpMapper;

	public List<List<Help>> getAll() {
		List<List<Help>> helps = (List<List<Help>>) CacheUtils.get(CacheConstants.HELP_CENTER);
		if (helps != null) return helps;
		helps = new ArrayList<>();//用于前台显示的菜单集合
		List<Help> parents = getOneLevels();//一级菜单集合
		for (Help help : parents) {
			help.setContent("");
			List<Help> helpTwo = new ArrayList<>();//一级菜单+该菜单的二级菜单集合
			List<Help> helpTwos = getByParentId(help.getId());//二级菜单集合
			helpTwo.add(help);
			for (Help help1 : helpTwos)//组装一级菜单和二级菜单
			{
				help1.setContent("");
				helpTwo.add(help1);
			}
			helps.add(helpTwo);
		}
		if (helps.size() > 0) {
			CacheUtils.set(CacheConstants.HELP_CENTER, helps, CacheConstants.HELP_CENTER_TIME);
		}
		return helps;
	}

	public List<Help> getOneLevels() {
		Help help = new Help();
		help.setParentId(0L);
		return getList(help);
	}

	public int delete(Long id) {
		int row = helpMapper.deleteById(id);
		if (row > 0) CacheUtils.remove(CacheConstants.HELP_CENTER);
		return row;
	}

	public Help get(Long id) {
		return helpMapper.selectById(id);
	}

	@Override
	public List<Help> getList(Help help) {
		return helpMapper.selectList(help);
	}

	@Override
	public int insert(Help help) {
		help.setCreateTime(LocalDateTime.now());
		return helpMapper.insertHelp(help);
	}

	@Override
	public int update(Help help) {
		int i = helpMapper.updateHelp(help);
		CacheUtils.remove(CacheConstants.HELP_CENTER);
		return i;
	}

	@Override
	public List<Ztree> getTree() {
		List<Help> list = getOneLevels();
		List<Ztree> zeroes = new ArrayList<>();
		for (Help helps : list) {
			Ztree ztree = new Ztree();
			ztree.setId(helps.getId());
			ztree.setpId(helps.getParentId());
			ztree.setName(helps.getName());
			ztree.setTitle(helps.getName());
			zeroes.add(ztree);
		}
		return zeroes;
	}

	@Override
	public List<Help> getByParentId(Long id) {
		Help help = new Help();
		help.setParentId(id);
		return helpMapper.selectList(help);
	}

}

